package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.entity.dto.TokenUserInfoDTO;
import com.easychat.entity.enums.*;
import com.easychat.entity.po.GroupInfo;
import com.easychat.entity.po.UserContact;
import com.easychat.entity.query.GroupInfoQuery;
import com.easychat.entity.query.UserContactQuery;
import com.easychat.entity.vo.GroupInfoVO;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.exception.BusinessException;
import com.easychat.service.GroupInfoService;
import com.easychat.service.UserContactService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 群组信息 Controller
 */
@RestController("groupController")
@RequestMapping("/group")
@Validated
public class GroupController extends ABaseController{
    //TODO DONE
    @Resource
    private GroupInfoService groupInfoService;
    @Resource
    private UserContactService userContactService;

    /**
     * 创建群组
     * @param request
     * @param groupId
     * @param groupName
     * @param groupNotice
     * @param joinType
     * @param avatarFile 头像文件
     * @param avatarCover 头像封面，缩略图
     * @return
     */
    @RequestMapping("/saveGroup")
    @GlobalInterceptor
    public ResponseVO saveGroup(
            HttpServletRequest request,  //需要获取请求header中的token
            String groupId,
            @NotEmpty String groupName,
            String groupNotice,
            @NotNull Integer joinType,
            MultipartFile avatarFile,
            MultipartFile avatarCover
    ) throws IOException {
        TokenUserInfoDTO tokenUserInfoDTO = getTokenUserInfoDTO(request);
        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setGroupId(groupId);
        groupInfo.setGroupName(groupName);
        groupInfo.setGroupOwnerId(tokenUserInfoDTO.getUserId());
        //groupInfo.setCreateTime(new Date());
        groupInfo.setGroupNotice(groupNotice);
        groupInfo.setJoinType(joinType);
        groupInfoService.saveGroup(groupInfo, avatarFile, avatarCover);
        return getSuccessResponseVO(null);
    }

    /**
     * 获取我创建的群组
     * @return
     */
    @RequestMapping("/loadMyGroup")
    @GlobalInterceptor
    public ResponseVO<List<GroupInfo>> loadMyGroup(HttpServletRequest request) {
        TokenUserInfoDTO tokenUserInfoDTO = getTokenUserInfoDTO(request);
        GroupInfoQuery groupInfoQuery = new GroupInfoQuery();
        groupInfoQuery.setGroupOwnerId(tokenUserInfoDTO.getUserId());
        groupInfoQuery.setOrderBy("create_time desc");
        List<GroupInfo> groupInfoList = groupInfoService.findListByParam(groupInfoQuery);
        return getSuccessResponseVO(groupInfoList);
    }

    /**
     * 获取群聊详情
     * @param request
     * @param groupId
     * @return
     */
    @RequestMapping("/getGroupInfo")
    @GlobalInterceptor
    public ResponseVO<GroupInfo> getGroupInfo(HttpServletRequest request, @NotNull String groupId) {
        //根据groupId查询群组信息
        GroupInfo groupInfo = getGroupInfoCommon(request, groupId);
        //查询群聊成员个数
        UserContactQuery userContactQuery = new UserContactQuery();
        userContactQuery.setContactId(groupId);
        Integer groupMemberCount = userContactService.findCountByParam(userContactQuery);
        groupInfo.setMemberCount(groupMemberCount);
        return getSuccessResponseVO(groupInfo);
    }

    /**
     * 获取聊天会话群聊详情
     * @param request
     * @param groupId
     * @return
     */
    @RequestMapping("/getGroupInfo4Chat")
    @GlobalInterceptor
    public ResponseVO<GroupInfo> getGroupInfo4Chat(HttpServletRequest request, @NotNull String groupId) {
        //根据groupId查询群组信息
        GroupInfo groupInfo = getGroupInfoCommon(request, groupId);
        //根据groupId查询联系人表
        UserContactQuery userContactQuery = new UserContactQuery();
        userContactQuery.setContactId(groupId);
        userContactQuery.setOrderBy("create_time asc");
        userContactQuery.setStatus(UserContactStatusEnum.FRIEND.getStatus());
        //是否关联用户信息
        userContactQuery.setQueryUserInfo(true);
        List<UserContact> userContactList = userContactService.findListByParam(userContactQuery);
        //封装VO对象
        GroupInfoVO groupInfoVO = new GroupInfoVO();
        groupInfoVO.setGroupInfo(groupInfo);
        groupInfoVO.setUserContactList(userContactList);
        return getSuccessResponseVO(groupInfoVO);
    }

    /**
     * 添加用户到群聊/移除群聊中的用户
     * @param groupId 群id
     * @param selectContacts 选择的联系人id
     * @param opType 操作类型 0移除 1添加
     * @return
     */
    @RequestMapping("/addOrRemoveGroupUser")
    @GlobalInterceptor
    public ResponseVO addOrRemoveGroupUser(
                HttpServletRequest request,
                @NotEmpty String groupId,
                @NotEmpty String selectContacts,
                @NotNull Integer opType
    ) {
        TokenUserInfoDTO tokenUserInfoDTO = getTokenUserInfoDTO(request);
        groupInfoService.addOrRemoveGroupUser(tokenUserInfoDTO, groupId, selectContacts, opType);
        return getSuccessResponseVO(null);
    }

    /**
     * 离开群聊
     * @param request
     * @param groupId
     * @return
     */
    @RequestMapping("/leaveGroup")
    @GlobalInterceptor
    public ResponseVO leaveGroup(HttpServletRequest request, @NotEmpty String groupId) {
        TokenUserInfoDTO tokenUserInfoDTO = getTokenUserInfoDTO(request);
        groupInfoService.leaveGroup(tokenUserInfoDTO.getUserId(), groupId, MessageTypeEnum.LEAVE_GROUP);
        return getSuccessResponseVO(null);
    }

    /**
     * 解散群组
     * @param groupId
     * @return
     */
    @RequestMapping("/dissolutionGroup")
    @GlobalInterceptor
    public ResponseVO dissolutionGroup(HttpServletRequest request, @NotEmpty String groupId) {
        TokenUserInfoDTO tokenUserInfoDTO = getTokenUserInfoDTO(request);
        groupInfoService.dissolutionGroup(tokenUserInfoDTO.getUserId(), groupId);
        return getSuccessResponseVO(null);
    }


    private GroupInfo getGroupInfoCommon(HttpServletRequest request, String groupId) {
        TokenUserInfoDTO tokenUserInfoDTO = getTokenUserInfoDTO(request);
        //请求发起者的id要和groupID对应，即用户要在群里才能获取群聊详情
        UserContact userContact = userContactService.getUserContactByUserIdAndContactId(tokenUserInfoDTO.getUserId(), groupId);
        if (userContact == null || !userContact.getStatus().equals(UserContactStatusEnum.FRIEND.getStatus())) {
            //联系人表中无信息 || 联系人状态不是好友
            throw new BusinessException("你不在此群聊中，或者群聊不存在/已解散");
        }
        //根据groupId查询群组信息
        GroupInfo groupInfo = groupInfoService.getGroupInfoByGroupId(groupId);
        if (groupInfo == null || groupInfo.getStatus().equals(GroupStatusEnum.DISBAND.getStatus())) {
            //没有此groupId的信息 || 状态为已解散
            throw new BusinessException("群聊不存在/已解散");
        }
        return groupInfo;
    }
}
